package cn.edu.hunau.oop.day09;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileAttribute;

/**
 * @author hb
 * @date 2025-08-14 14:46:03
 */
public class TestFile {

    @Test
    public void test01(){
        //点好表示当前的目录
        File f1=new File(".");//File当前目录为当前工程下面
        System.out.println("绝对路径："+f1.getAbsolutePath());
        System.out.println("名称："+f1.getName());//.
        System.out.println("是否为目录："+f1.isDirectory());//true
        System.out.println("是否在磁盘中存在："+f1.exists());//true
    }

    @Test
    public void testCreate() throws IOException {
        //相对路径：在当前目录下创建一个dir的实例对象
        File f1=new File("dir");
        if(!f1.exists()){//如果磁盘中不存在
           f1.mkdir();//创建对应的目录
        }
        //在dir的目录中创建一个a01.txt文件
        //File f2=new File(f1,"a01.txt");
        File f2=new File("dir/a01.txt");
        if(!f2.exists()){
            f2.createNewFile();//创建文件
        }
        System.out.println("是否为文件："+f2.isFile());
        System.out.println("是否可操作："+f2.canExecute());
        //修改文件的名称
        f2.renameTo(new File("dir/a001.txt"));

        Path path = f2.toPath();
        File f3 = path.toFile();
    }

    @Test
    public void filesTest() throws IOException {
        Path temp = Path.of("temp");
        if(!Files.exists(temp)){
            Path tempDir = Files.createDirectory(Path.of("temp"));
        }

        Files.createFile(Path.of("temp/t01.txt"));
    }

    @Test
    public void testDelete() throws IOException {
      Files.deleteIfExists(Path.of("temp/t01.txt"));
      boolean isDelete=  Files.deleteIfExists(Path.of("temp"));
    }

    @Test
    public void testRead() throws IOException {
        try(FileInputStream fis=new FileInputStream("dir/a001.txt");){
            //声明byte数组
            byte[] buff=new byte[1024];
            int count = fis.read(buff);
            //将byte转成字符串
            String content = new String(buff,0,count);
            System.out.println(content);
        }
    }
}
